﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using iHouse.Common.Configuration;
using iHouse.Common.Const;
using iHouse.Common.Helper;
using iHouse.Infrastructure;
using iHouse.Model.Data;
using iHouse.Model.Repository.Interface;
using iHouse.Web.Infrastructure;
using Microsoft.Practices.Unity;

namespace iHouse.Web.Controllers
{
    public class BookController : BaseController
    {
        #region Properties
        protected override int DefaultPageSize
        {
            get
            {
                return IHouseSection.Current.Book.PageSize;
            }
        }

        protected override string HomeView
        {
            get
            {
                return "HomeList";
            }
        }

        [Dependency]
        public IBookRepository BookRespository { get; set; }

        [Dependency]
        public IPublisherRepository PublisherRespository { get; set; }

        protected override CategoryType ControllerType
        {
            get { return CategoryType.Book; }
        }

        private IEnumerable<Publisher> Publishers
        {
            get
            {
                return PublisherRespository.GetPublishers();
            }
        }
        #endregion

        #region Actions

        public ActionResult HomeList(int? category, int? page, [PaingCriteriaBinder(typeof(BookSearchFilter))]PagingCriteria pagingCriteria)
        {
            PaginationList<Book> result = null;

            if (category.HasValue)
            {
                result = this.BookRespository.FindEntitiesByCategory(category.Value, page.HasValue ? page.Value : 1, DefaultPageSize);
            }
            else
            {
                pagingCriteria.PageSize = DefaultPageSize;
                pagingCriteria.PageIndex = page.HasValue ? page.Value : 1;
                result = this.BookRespository.FindEntities(pagingCriteria);
            }

            return View(result);
        }

        public ActionResult Detail(int? bookID)
        {
            var bookEntity = this.BookRespository.GetBookByID(bookID.Value);

            return View(bookEntity);
        }

        [Authorize]
        public ActionResult Create()
        {
            Book book = new Book();

            return View(ViewConst.BOOK_EDIT, ConstrustBookView(book));
        }

        [Authorize]
        [HttpPost]
        public ActionResult Create(Book book)
        {
            if (ModelState.IsValid)
            {
                this.BookRespository.CreateBook(book);

                var result = this.BookRespository.FindEntitiesByCategory(book.CategoryID.GetValueOrDefault(), 1, this.DefaultPageSize);

                return PartialView(ViewConst.BOOK_SHELF, result);
            }

            return View(ConstrustBookView(book));
        }

        [Authorize]
        public ActionResult Edit(int? bookID)
        {
            Book book = this.BookRespository.GetBookByID(bookID.GetValueOrDefault());

            return View(ConstrustBookView(book));
        }

        [Authorize]
        [HttpPost]
        public ActionResult Edit(int? bookID, int? category, int page, FormCollection form)
        {
            Book book = this.BookRespository.GetBookByID(bookID.GetValueOrDefault());

            try
            {
                UpdateModel(book, "Book");

                if (ModelState.IsValid)
                {
                    this.BookRespository.UpdateBook();

                    int count = this.BookRespository.GetBookCountByCategoryAndPage(category.GetValueOrDefault(), page, this.DefaultPageSize);
                    if (count == 0 && page > 1)
                    {
                        page = page - 1;
                    }

                    PaginationList<Book> result;
                    if (category.GetValueOrDefault() > 0)
                    {
                        result = this.BookRespository.FindEntitiesByCategory(category.GetValueOrDefault(), page, this.DefaultPageSize);
                    }
                    else
                    {
                        result = this.BookRespository.FindEntities(new PagingCriteria() { PageIndex = page, PageSize = this.DefaultPageSize });
                    }


                    return PartialView(ViewConst.BOOK_SHELF, result);
                }

                return View(ConstrustBookView(book));
            }
            catch
            {
                return View(ConstrustBookView(book));
            }
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete(int? bookID, int? category, int page)
        {
            if (bookID.GetValueOrDefault() > 0)
            {
                this.BookRespository.DeleteBook(bookID.GetValueOrDefault());

                int count = this.BookRespository.GetBookCountByCategoryAndPage(category.GetValueOrDefault(), page, this.DefaultPageSize);
                if (count == 0 && page > 1)
                {
                    page = page - 1;
                }

                PaginationList<Book> result;
                if (category.GetValueOrDefault() > 0)
                {
                    result = this.BookRespository.FindEntitiesByCategory(category.GetValueOrDefault(), page, this.DefaultPageSize);
                }
                else
                {
                    result = this.BookRespository.FindEntities(new PagingCriteria() { PageIndex = page, PageSize = this.DefaultPageSize });
                }

                if (this.Request.IsAjaxRequest())
                {
                    return PartialView(ViewConst.BOOK_SHELF, result);
                }
                else
                {
                    return View(ViewConst.BOOK_LIST, result);
                }
            }
            else
            {
                return View(ViewConst.ERROR, new { controller = "book", action = "deletebook", message = "idwrong" });
            }
        }

        [Authorize]
        public ActionResult Upload(int? bookID)
        {
            Book book = this.BookRespository.GetBookByID(bookID.GetValueOrDefault());

            return View(book);
        }

        [Authorize]
        [HttpPost]
        public ActionResult UploadImage(HttpPostedFileBase image, int? bookID)
        {
            try
            {
                string defaultFolder = FileHelper.CheckPathEndWith(IHouseSection.Current.Upload.BookFolder);

                string physicalPath = FileHelper.CheckPathEndWith(Server.MapPath(defaultFolder));
                string[] list = image.FileName.Split('\\');

                image.SaveAs(string.Format("{0}{1}", physicalPath, list.Last()));

                string imagePath = string.Format("{0}{1}", defaultFolder, list.Last());

                Book book = this.BookRespository.GetBookByID(bookID.GetValueOrDefault());
                book.ImagePath = imagePath;

                this.BookRespository.UpdateBook();

                return Content(ActionConst.PARENT_PAGE_RELOAD);
            }
            catch (Exception ex)
            {
                return View(ViewConst.ERROR, new HandleErrorInfo(ex, "Book", "UploadImage"));
            }
        }
        #endregion

        private BookFormView ConstrustBookView(Book book)
        {
            return new BookFormView
            {
                Categories = new SelectList(this.Categories, "ID", "Name", book.CategoryID),
                Publishers = new SelectList(this.Publishers, "ID", "Name", null),
                Book = book,
            };
        }
    }
}